<template>
  <el-row class="home" :gutter="20">
    <!--题目显示区-->
    <el-col v-model="detail" :span="12" style="margin-top: 20px">
      <!--题目头部-->
      <el-card>
        <div class="title">
          <div class="l-title">
            <el-tag effect="light" style="margin-right: 10px">{{detail.num}}</el-tag>
            <span style="margin-left: 10px; font-weight: bold; font-size: 22px">{{detail.title}}</span>
          </div>
          <div class="r-title">
          </div>
        </div>
      </el-card>
      <!--题目详细信息-->
      <el-card >
        <div class="login-info">
          <h4><span>{{detail.title}}</span></h4>
          <el-divider></el-divider>

            <mavon-editor
                    class="description"
                    :value="detail.context"
                    :subfield="false"
                    defaultOpen="preview"
                    :toolbarsFlag="false"
                    :editable="false"
                    :scrollStyle="true"
                    style="min-height:100px">
            </mavon-editor>

          <el-divider></el-divider>
          <!--样例展示-->
          <el-card class="demo" v-for="(it, index) in test">
            <h4>输入示例{{index+1}}</h4>

            <h4>输出示例{{index+1}}</h4>
            <el-alert type="success" :closable="false"><span>{{it.output}}</span></el-alert>
          </el-card>
        </div>
      </el-card>
    </el-col>

    <!--代码输入区-->
    <el-col :span="12" style="margin-top: 20px">
      <!--功能区-->
      <el-card>
        <div class="tool">
          <el-button type="success" @click="toCompile" size="small" :disabled="stopCommit">提交</el-button>
<!--          <el-button type="success" size="small">执行</el-button>-->
        </div>
      </el-card>
      <!--代码编辑框-->
      <el-card class="tool">
        <div>
          <CodeMirror ref="codeMirror"></CodeMirror>
        </div>
      </el-card>
      <!--编译执行结果-->
      <el-card class="result">
        <!--显示结果与错误信息-->
        <div>
          <div class="okInfo" v-if="ok" style="width: 100%">
<!--显示执行结果-->

<pre>
执行结果：<span><el-button type="success" plain size="small">通过</el-button></span>
</pre>
            <el-alert
                    type="success"
                    :closable="false"
                    style="width: 100%; height: auto">
              <pre>{{result}}</pre>
            </el-alert>
<!--仿照leetcode的写法，但是现在暂时不用-->
<!--<pre>-->
<!--执行结果：<span><el-button type="success" plain size="small">通过</el-button></span>-->
<!--执行用时：<span style="font-weight: bold">1ms</span>，在所有提交中击败了<span style="font-weight: bold">97.82%</span>的用户-->
<!--内存消耗：<span style="font-weight: bold">41.4MB</span>，在所有提交中击败了<span style="font-weight: bold">22.01%</span>的用户-->
<!--通过测试用例：<span style="font-weight: bold">34</span>/<span style="font-weight: bold">34</span>-->
<!--</pre>-->
          </div>
          <div class="errorInfo" v-if="error" style="width: 100%">
<pre>
执行结果：<span><el-button type="danger" plain size="small">编译错误</el-button></span>
</pre>
            <el-alert
                    type="error"
                    :closable="false"
                    style="width: auto; height: 100%">
              <pre v-for="(it, index) in errorMsg" :key="index">{{it}}</pre>
            </el-alert>
          </div>
        </div>
        <el-divider></el-divider>
        <div>
          <el-table
                  :data="paperList"
                  stripe
                  style="width: 100%">
            <el-table-column
                    prop="status"
                    label="提交结果"
                    width="120px"
                    :formatter="statusFormat">
            </el-table-column>
            <el-table-column
                    prop="timeLimit"
                    label="执行用时"
                    align="center"
                    width="120px">
            </el-table-column>
            <el-table-column
                    prop="memoryLimit"
                    label="内存消耗"
                    align="center"
                    width="120px">
            </el-table-column>
            <el-table-column
                    prop="createTime"
                    label="提交时间" >
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </el-col>
  </el-row>
</template>

<script>
// 引用刚刚写的codemirror.vue公共组件
import CodeMirror from '../../components/CodeMirror'
//axios
import axios from 'axios'

export default {
  name: 'HomePage',
  components: {
    CodeMirror
  },
  data() {
    return {
      result: '',  //执行结果
      errorMsg: [],//错误信息
      code: '',    //源代码

      //表格内容
        paperList: [],
          //显示
       ok: false,
       error: false,
       stopCommit: false,   //是否可以提交
       detail: {},          //题目详情
       test: [],              //样例详情
      token: '',
      questionId: '',
    }
  },
  mounted() {
    this.connectWebsocket();
  },
  methods: {
    statusFormat(row, column) {
      if (row.status == "1") {
        return 'ok'
      } else if (row.status == "2") {
        return 'error'
      } else{
        return 'compile'
      }
    },
    // 刷新 （如果出现编辑器样式问题，以及不能初始化赋值回显数据，可以进行刷新操作）
    refresh() {
      this.$refs.codeMirror.refresh()
    },
    // 获取编辑器的值
    getValue() {
      return this.$refs.codeMirror.code
    },
    // 回显赋值
    setValue() {
      this.$refs.codeMirror.setValue('回显的值:比如 function aa() {}')
    },
    //学生编译请求
    toCompile: function () {
      var that = this;
      //重置数据
      this.result = '';
      this.errorMsg = [];
      this.ok = false;
      this.error = false;

      //发送请求
      /*
          接口: 学生编译
          请求地址: http://localhost:8881/producer/common/compile
          请求方法: post
          请求参数: source（源代码，字符串），args（方法参数，字符串数组）
          响应内容: 编译结果
      */
      this.code = this.$refs.codeMirror.code;
      console.log(this.code)
      axios({
        method: 'post',
        url: 'http://localhost:8881/producer/common/compile',
        data: {
          source: this.code,
          questionId: this.questionId
        },
        headers: {
          token: this.token
        }
      }).then(function (response) {
        var res = response.data;
        if (res.code == 200) {
          that.$message.success('提交成功！');
        } else {
          that.$message.error('提交失败！');
        }
        //TODO 处理paper请求接口，更新提交列表，过多则用滚轮显示
      }).catch(function (error) {
        console.log(error);
      });
    },
    connectWebsocket() {
      let websocket;
      let that = this;

      if (typeof WebSocket === "undefined") {
        console.log("您的浏览器不支持WebSocket");
        return;
      } else {
        let protocol = "ws";
        let url = "";
        if (window.location.protocol == "https:") {
          protocol = "wss";
        }
        // `${protocol}://window.location.host/echo`;
        //url = 'ws://localhost:8080/api/websocket/100';
        url = `${protocol}://localhost:8882/consume/webSocket/` + this.questionId;

        // 打开一个websocket
        websocket = new WebSocket(url);
        // 建立连接
        websocket.onopen = () => {
          // 发送数据
          websocket.send("Hi, I am client !");
          console.log("websocket发送数据中...");
        };
        // 客户端接收服务端返回的数据
        websocket.onmessage = evt => {
          console.log("websocket返回的数据：", evt);
          var res = evt.data;
          res = JSON.parse(res);
          if(res.code == 200){
            that.result = res.data.res;
            that.errorMsg = '编译成功';
            that.ok = true;
          }else{
            that.errorMsg = res.data.detailMsg;
            that.error = true;
          }
        };
        // 发生错误时
        websocket.onerror = evt => {
          console.log("websocket错误：", evt);
        };
        // 关闭连接
        websocket.onclose = evt => {
          console.log("websocket关闭：", evt);
        };
      }
    },
  },
    created: function () {
        //初始化页面
        var id = this.$route.query.id;
        let params = {questionId: id};
        var that = this;
      let token = localStorage.getItem('token');
      this.token = token;
      this.questionId = id;
      console.log("data,id" + this.questionId)

              //发送请求
        /*
            接口: 根据id获取题目信息
            请求地址: http://localhost:8881/producer/question/select
            请求方法: post
            请求参数: 查询条件
            响应内容: 响应结果
        */
        axios({
            method: 'post',
            url: 'http://localhost:8881/producer/question/select',
            data: params,
          headers: {
            token: token
          }
        }).then(function (response) {
            var res = response.data;
            if(res.code == 200){
                that.detail = res.data.questionList[0];
            }else{
                that.$message.error('数据获取失败！');
            }
        }).catch(function (error) {
            console.log(error);
        });

        //发送请求
        /*
            接口: 根据id获取样例信息
            请求地址: http://localhost:8881/producer/test/select
            请求方法: post
            请求参数: 查询条件
            响应内容: 响应结果
        */
        axios({
            method: 'post',
            url: 'http://localhost:8881/producer/test/select',
            data: params,
          headers: {
            token: token
          }
        }).then(function (response) {
            var res = response.data;
            if(res.code == 200){
                that.test = res.data.testList;
            }else{
                that.$message.error('数据获取失败！');
            }
        }).catch(function (error) {
            console.log(error);
        });

        //发送请求
        /*
            接口: 根据id获取做题信息
            请求地址: http://localhost:8881/producer/paper/select/by/uid
            请求方法: post
            请求参数: 查询条件
            响应内容: 响应结果
        */
        axios({
            method: 'post',
            url: 'http://localhost:8881/producer/paper/select/by/uid',
            data: params,
          headers: {
            token: token
          }
        }).then(function (response) {
            var res = response.data;
            if(res.code == 200){
                that.paperList = res.data.paperList;
            }else{
                that.$message.error('数据获取失败！');
            }
        }).catch(function (error) {
            console.log(error);
        });
    }
}
</script>

<style lang="less" scoped>
.title {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.l-title {
  display: flex;
  align-items: center;
}

.r-title {
}
.description {
  white-space: pre-wrap;
}


</style>
